<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Action</title>
  </head>
  <body>
    <div id="app">
      <p>count:{{count}}</p>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
    <script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
    <script>
      var store = new Vuex.Store({
        state: { count: 1 },
        mutations: {
          increase(state) {
            state.count++;
          },
          decrease(state) {
            state.count--;
          },
        },
        actions: {
          increaseAsyncInAction(context) {
            //让action方法返回一个Promise
            return new Promise((resolve) => {
              setTimeout(() => {
                //1s后提交mutation,更新状态，让Promise成功
                context.commit("increase");
                resolve();
              }, 1000);
            });
          },
          decreaseAsyncInAction(context) {
            return new Promise((resolve) => {
              setTimeout(() => {
                context.commit("decrease");
                resolve();
              }, 1000);
            });
          },
        },
      });
     /*  console.log(store.state.count); //1
      store.dispatch("increaseAsyncInAction")
      .then(()=>{
        console.log(store.state.count); //2
        return store.dispatch("decreaseAsyncInAction");
      }).then(()=>{
        console.log(store.state.count); //1
      }); */

      (async function(){
        console.log(store.state.count); //1
        //等待promise成功，成功之后才会继续向后执行
        await store.dispatch("increaseAsyncInAction")
        console.log(store.state.count); //2
        await store.dispatch("decreaseAsyncInAction");
        console.log(store.state.count);

       // Promise.all([promise1,promise2]); 并行的
      })();
     
      
     

      //要实现先加1再减少1
      /*  
     console.log(store.state.count);//1
      store.commit('increase');
      console.log(store.state.count);//2
      store.commit('decrease');
      console.log(store.state.count);//1 */
    </script>
  </body>
</html>
